from dao.DAOQuanLyNhanVien import DaoQuanLyNhanVien
import json as simplejson
import WSGI
import logging
import math
import webapp2
from google.appengine.api import users
from utils.permission_required import permission_required

logger = logging.getLogger("GUIBaoCaoDoanhThu")

class GuiBaoCaoDoanhThu(webapp2.RequestHandler):
    
    perm = 'KeToan.BaoCaoDoanhThu'
    priv = ''
    @permission_required
    def get(self):
        if self.priv in ['Owner', 'Accounting']:
            cbbTenNV, _ = DaoQuanLyNhanVien.getListNhanVien('', '', 1000, 0, '')
        else:
            user = users.get_current_user()
            nhanVien = DaoQuanLyNhanVien.getNhanVienByUsername(user.nickname())
            cbbTenNV, _ = DaoQuanLyNhanVien.getListNhanVien('', '', 1000, 0, nhanVien.key().id())
        for item in cbbTenNV:
            item['tenNV'] = str(item['id']) + ' - ' + item['tenNV']
        lstTenNVText = ''
        for item in cbbTenNV:
            lstTenNVText += str(item['id']) + ':' + item['tenNV'] + ';'
        lstTenNVText = lstTenNVText[:-1]
        
        nv = DaoQuanLyNhanVien.getNhanVienByUsername(users.get_current_user().nickname())
        lstPerm = DaoQuanLyNhanVien.getListStaffPriviledge(nv.key().id())
        lstMenu = []
        lstNewPerm = []
        for perm in lstPerm:
            lstMenu.append(perm[:perm.index('.')])
            lstNewPerm.append(perm.replace('.', '-'))
        lstMenu = list(set(lstMenu))
        
        template_values = {
                        'lstPerm': lstNewPerm,
                        'lstMenu': lstMenu,
                        'priv': self.priv,
                        'lstNhanVien': cbbTenNV,
                        'lstTenNVText':lstTenNVText,
                        'nickname': users.get_current_user().nickname(),
                        'signOutUrl': users.create_logout_url(self.request.uri)
        }

        template = WSGI.jinja_environment.get_template('/html/BaoCaoDoanhThu.html')
        self.response.out.write(template.render(template_values))


class JsonRequestHandler(webapp2.RequestHandler):
    perm = 'KeToan.BaoCaoDoanhThu'
    priv = ''
    @permission_required
    def get(self):
        funcName = self.request.get('func')
        funcMapping = {'getListDoanhThu': 'getListDoanhThu'}
        func = getattr(self, funcMapping[funcName]);
        result = func();
        self.response.out.write(result)
    
    def post(self):
        return self.get()
    
    def getListDoanhThu(self):
        gridRowNum = int(self.request.get('rows'))
        pageNum = int(self.request.get('page'))
        idNV = self.request.get('maNhanVien')
        idKH = self.request.get('maKhachHang')
        fromDate = self.request.get('tuNgay')
        toDate = self.request.get('denNgay')
        
        rows, rowNum = DaoQuanLyNhanVien.getListDoanhThu(idNV, idKH, fromDate, toDate, gridRowNum, int((pageNum-1)*gridRowNum))
        rs = []
        for item in rows:
            item['tenNV'] = str(item['maNV']) + ' - ' + item['tenNV']
            item['tenKH'] = str(item['maKH']) + ' - ' + item['tenKH']
            item['congNo'] = item['doanhThu'] - item['tongThu']
            flag = True
            for element in rs:
                if element['tenKH'] == item['tenKH']:
                    element['doanhThu'] += item['doanhThu']
                    element['tongThu'] += item['tongThu']
                    element['congNo'] += item['congNo']
                    flag = False
            if flag == True:
                rs.append(item)
                
        results = {'page': pageNum, 'total': math.ceil(float(rowNum)/gridRowNum), 'records':rowNum, 'rows':rows}
        return simplejson.dumps(results)

        
        
            
        